package com.ossjk.oa.system.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.ossjk.core.base.controller.BaseController;
import com.ossjk.core.util.CommonUtil;
import com.ossjk.core.util.Constant;
import com.ossjk.oa.system.entity.Dictionary;
import com.ossjk.oa.system.service.IDictionaryService;

/**
 * <p>
 * 系统属性 前端控制器
 * </p>
 *
 * @author chair
 * @since 2019-01-14
 */
@RestController
@RequestMapping("/system/attribute")
public class AttributeController extends BaseController {
	@Autowired
	private IDictionaryService iDictionaryService;

	@RequiresPermissions("00000025")
	@GetMapping("/list")
	public Object list() {
		// 前端倒序增加所以搜索时根据倒序查询
		Wrapper wrapper = Condition.create().like("type", "1").orderBy("crtm", false);
		return responseSuccess(iDictionaryService.selectList(wrapper));
	}

	@RequiresPermissions("000000250000")
	@PutMapping("/update")
	public Object update(String[] id, String[] dvalue) {
		if (!CommonUtil.isBlank(id)) {
			List<Dictionary> dictionaries = new ArrayList();
			for (int i = 0; i < id.length; i++) {
				Dictionary dictionary = new Dictionary();
				dictionary.setId(id[i]);
				dictionary.setDvalue(dvalue[i]);
				dictionaries.add(dictionary);
			}
			if (iDictionaryService.updateBatchById(dictionaries)) {
				Map attributeMap = new HashMap();
				Wrapper wrapper = Condition.create().like("type", "1").orderBy("crtm", false);
				List<Dictionary> dictionaries2 = iDictionaryService.selectList(wrapper);
				for (Dictionary dictionary : dictionaries2) {
					attributeMap.put(dictionary.getDkey(), dictionary.getDvalue());
				}
				getRequest().getServletContext().setAttribute(Constant.APPLICATION_ATTRIBUTE_KEY, attributeMap);
				return responseSuccess();
			} else {
				return responseFail();
			}
		}
		return responseSuccess();

	}

}
